package com.suns.commom;

import com.suns.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/*
HandlerInterceptorAdapter ?  （处理器）拦截器适配器
实现 HandlerInterceptor 处理器拦截器
 */

/**
 * 本类继承自 拦截器适配器HandlerInteceptorAdapter
 * 需要被spring管理，到spring-servlet.xml中进行配置
 *
 * 可以计算请求完成时间 （在请求处理前计时 ，在请求完成后计时 ，运算）
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
    private static String START_TIME = "requestStartTime";
    /**
     * 请求处理前
     * 将请求内的参数打印进日之内时应对敏感信息进行过滤
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request start. url:{}, params:{}", url, JsonMapper.obj2String(parameterMap));
        long star = System.currentTimeMillis();
        request.setAttribute(START_TIME, star);
        return true;
    }

    /**
     * 请求正常结束后
     * 可根据需求进行使用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        /*String url = request.getRequestURI().toString();
        long start = (long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        log.info("request end success. url:{}, cost:{}", url, end - start);*/
    }

    /**
     * 整个请求结束后（异常也会运行）
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURI().toString();
        long start = (long) request.getAttribute(START_TIME);
        long end = System.currentTimeMillis();
        log.info("request finally end.  url:{}, params:{}", url, end - start);
    }
}
